package com.huawei.esdk.uc.sametime.uccallbackimpl;

import java.util.Map;

import org.apache.log4j.Logger;
import org.eclipse.swt.widgets.Display;

import com.huawei.esdk.uc.jna.callback.StatusChangedCB;
import com.huawei.esdk.uc.jna.struct.STContact;
import com.huawei.esdk.uc.jna.util.StringUtil;
import com.huawei.esdk.uc.sametime.EsdkPluginActivator;
import com.huawei.esdk.uc.sametime.widgets.EsdkUCConvWindow;
import com.ibm.collaboration.realtime.people.Person;

public class UCStatusChangedCallBackImpl implements StatusChangedCB
{

    private Logger logger = Logger.getLogger(UCStatusChangedCallBackImpl.class);

    private static UCStatusChangedCallBackImpl instance = new UCStatusChangedCallBackImpl();

    public static UCStatusChangedCallBackImpl getInstance()
    {
        return instance;
    }

    private UCStatusChangedCallBackImpl()
    {

    }

    @Override
    public void callBack(int arg0, STContact arg1)
    {
        String ucAccount = StringUtil.bytesToString(arg1.ucAcc);

        logger.debug("UC StatusChanged " + ucAccount + " status is " + arg0);

        // 在sametime登录后,将sametime直接退出,这个时候,插件启动器类被释放,获取PersonMap,person操作会失效
        EsdkPluginActivator pluginActivator = EsdkPluginActivator.getDefault();
        Map<String, Person> personMap = null;

        if (null != pluginActivator)
        {
            personMap = pluginActivator.getPersonMap();
        }

        Person person = null;
        if (null != personMap)
        {
            person = personMap.get(ucAccount);
        }
        else
        {
            logger.warn("personmap in plugin activator released");
        }
        if (null != person)
        {
            person.refreshStatus();
        }

        FreshTableJob freshJob = new FreshTableJob();
        Display.getDefault().syncExec(freshJob);
    }

    private static class FreshTableJob implements Runnable
    {
        @Override
        public void run()
        {
            EsdkUCConvWindow.getInstance().freshTable();
        }
    }

}
